﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPFWorkbookDesigner.UI.Controls
{
    public class ComboboxItemWithCommand : ComboBoxItem, ICommandSource
    {
        public static readonly DependencyProperty CommandParameterProperty
            = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ComboboxItemWithCommand));
        public static readonly DependencyProperty CommandProperty
            = DependencyProperty.Register("Command", typeof(ICommand), typeof(ComboboxItemWithCommand));
        public static readonly DependencyProperty CommandTargetProperty
            = DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(ComboboxItemWithCommand));

        public ICommand Command
        {
            get
            {
                return (ICommand)GetValue(CommandProperty);
            }
            set
            {
                SetValue(CommandProperty, value);
            }
        }

        public object CommandParameter
        {
            get
            {
                return (object)GetValue(CommandParameterProperty);
            }
            set
            {
                SetValue(CommandParameterProperty, value);
            }
        }

        public IInputElement CommandTarget
        {
            get
            {
                return (IInputElement)GetValue(CommandTargetProperty);
            }
            set
            {
                SetValue(CommandTargetProperty, value);
            }
        }

        protected override void OnSelected(RoutedEventArgs e)
        {
            var command = Command;
            var parameter = CommandParameter;
            var target = CommandTarget;

            base.OnSelected(e);

            var routedCmd = command as RoutedCommand;
            if (routedCmd != null && routedCmd.CanExecute(parameter, target))
            {
                routedCmd.Execute(parameter, target);
            }
            else if (command != null && command.CanExecute(parameter))
            {
                command.Execute(parameter);
            }
            e.Handled = true;
        }
    }

    public class SpreadTabItem : TabItem
    {
        
    }
}